import { Component, Input, ElementRef, SimpleChanges, OnChanges, ViewChild, Renderer2 } from '@angular/core';
import { ICONS_ARRAY } from './icons';
import { find } from 'lodash';
@Component({
    selector: 'app-icon',
    template: '<div #iconSvg class="icon-container"></div>',
    styleUrls: ['./icon.component.less']
})
export class IconComponent implements OnChanges {

    @Input()
    width = 20;
    @Input()
    height = 20;
    @Input()
    name: string;
    @Input()
    color: string;
    @ViewChild('iconSvg')
    iconSvg: ElementRef;
    constructor(private renderer: Renderer2) { }

    ngOnChanges(changes: SimpleChanges): void {
        if (changes.firstChange) {
            return;
        }
        this.setIconAttr();
    }
    setIconAttr() {
        const iconSvg = this.iconSvg.nativeElement as HTMLElement;
        iconSvg.childNodes.forEach((node) => {
            iconSvg.removeChild(node);
        });
        const iconMap =  find(ICONS_ARRAY, ['name', this.name]);
        const svg = new DOMParser().parseFromString(iconMap.svg, 'text/html').body.children[0] as HTMLElement;
        this.renderer.setAttribute(svg, 'width', `${this.width}px`);
        this.renderer.setAttribute(svg, 'height', `${this.width}px`);
        iconSvg.appendChild(svg);
    }
}
